<template>
  <el-row>
    <div class="block">
      <el-date-picker v-model="value2" type="daterange" :shortcuts="shortcuts" range-separator="To" start-placeholder="起始日期" end-placeholder="结束日期"/>
    </div>
    <div class="block">
      <el-select v-model="value3" placeholder="选择区域" style="width: 240px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <div class="block">
      <el-radio-group v-model="timeView" @change="updateView">
        <el-radio :label="1" :class="{ active: timeView === 1 }" border>按小时</el-radio>
        <el-radio :label="2" :class="{ active: timeView === 2 }" border>按天</el-radio>
      </el-radio-group>
    </div>

  </el-row>
  <div>
    <el-card><div ref="chart" style="height: 300px; width: 1300px"></div></el-card>
    <el-card>
      <div ref="chart2" style="height: 300px; width: 1300px"></div>
    </el-card>
    <el-card>
      <el-button @click="exportToExcel">导出为 Excel</el-button>
      <el-table :data="tableData" border style="width: 100%">
    <el-table-column prop="production_date" label="日期" width="150"></el-table-column>
    <el-table-column prop="shift" label="班次" width="80"></el-table-column>
    <el-table-column prop="equipment_id" label="工位ID" width="100"></el-table-column>
    <el-table-column prop="sum" label="总产量" width="80"></el-table-column>
    <el-table-column prop="hour_01" label="小时1" width="80"></el-table-column>
    <el-table-column prop="hour_02" label="小时2" width="80"></el-table-column>
    <el-table-column prop="hour_03" label="小时3" width="80"></el-table-column>
    <el-table-column prop="hour_04" label="小时4" width="80"></el-table-column>
    <el-table-column prop="hour_05" label="小时5" width="80"></el-table-column>
    <el-table-column prop="hour_06" label="小时6" width="80"></el-table-column>
    <el-table-column prop="hour_07" label="小时7" width="80"></el-table-column>
    <el-table-column prop="hour_08" label="小时8" width="80"></el-table-column>
    <el-table-column prop="hour_09" label="小时9" width="80"></el-table-column>
    <el-table-column prop="hour_10" label="小时10" width="85"></el-table-column>
    <el-table-column prop="hour_11" label="小时11" width="85"></el-table-column>
    <el-table-column prop="hour_12" label="小时12" width="85"></el-table-column>
  </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, toRef, toRefs } from "vue";
import * as echarts from "echarts"; //引入echarts核心模块
import axios from "axios"; //引入echarts核心模块
import { useRouter } from "vue-router";
import XLSX from 'xlsx'; // 导入 xlsx
import { saveAs } from 'file-saver';


let lastPointId;
const value2 = ref([]);

const shortcuts = [
  {
    text: "近1周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    },
  },
  {
    text: "近2周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 14);
      return [start, end];
    },
  },
  {
    text: "近1月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    },
  },
];
const chart = ref(); 
const chart2 = ref();
const chartInstance2 = ref(null);
const series_data = ref();
const series_data1 = ref();
const timeView = ref(1); 
const tableData = ref([]);

const updateView = () => {
  useShowDataInHtmlForTable(lastPointId);
};

const initChart = async () => {
  if (chart.value == null) {
    return;
  }

  echarts.dispose(chart.value);
  var myChart = echarts.init(chart.value);
  myChart.setOption({});
  let option = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        // params 是一个数组，包含了所有在当前横坐标上的系列数据
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["总产量"],
      orient: "horizontal", // 改为水平显示
      left: "left", // 将图例放置在左侧
      top: "top", // 将图例放置在顶部
      itemGap: 10, // 图例项之间的间距
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ["line", "bar"] },
        restore: { show: true },
        saveAsImage: { show: true },
      },
    },

    title: {
      text: `${value3Label.value} 整线产量统计`,
      left: "center",
      subtext: "s",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data1.value,
      sort: 'ascending',
      axisLabel: {
            rotate: 45 // 将 x 轴标签倾斜 45 度
          }
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "总产量",
        data: series_data.value,
        type: "bar",
        stack:'total',
        color: "#59c4e6",
      },
    ],
  };
  myChart.on('click', (params) => {
    console.log('Clicked:', params);
    const equipment_id = params.name; 
    useShowDataInHtmlForTable(equipment_id);
  });
  myChart.setOption(option);
};

const initChart2 = async (pointId) => {
  if (chartInstance2.value == null) {
    return;
  }

  echarts.dispose(chartInstance2.value);
  var myChart2 = echarts.init(chartInstance2.value);
  myChart2.setOption({});

  let option2 = {
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        var result = "";
        for (var i = 0; i < params.length; i++) {
          var param = params[i];
          if (i === 0) {
            result += param.name + "<br/>";
          }
          result += param.seriesName + ": " + param.value + "<br/>";
        }
        return result;
      },
    },
    legend: {
      data: ["产量"],
      orient: "horizontal", 
      left: "left", 
      top: "top", 
      itemGap: 10, 
    },
    title: {
      text: `${pointId} 工位产量情况`,
      left: "center",
      textStyle: {
        color: "black", 
      },
      subtextStyle: {
        fontWeight: "bold",
      },
    },
    xAxis: {
      type: "category",
      data: series_data3.value,
      
    },
    dataZoom: [
      {
        type: "slider", 
        start: 0, 
        end: 100, 
      },
      {
        type: "inside", 
        start: 90, 
        end: 100, 
      },
    ],
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "产量",
        data: series_data4.value,
        type: "bar",
        color: "#5470c6",
        stack: 'toatl'
      },
    ],
  };
  myChart2.setOption(option2);
};

onMounted(() => {
  const oneWeekAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
  const today = new Date();
  value2.value = [oneWeekAgo, today];
  use_show_data_in_html2();
  chartInstance2.value = chart2.value; 
  initChart2();
  useShowDataInHtmlForTable("1010");
});

const value3 = ref("CAS01");
const value3Label = ref("装配A");
const router = useRouter();
const options = [
  { value: "CAS01", label: "装配A" },
  { value: "CAH01", label: "装配B" },
  { value: "CAC01", label: "装配C" },
  { value: "CBK01", label: "缸体M1" },
  { value: "CBK02", label: "缸体M2" },
  { value: "CHD01", label: "缸盖M1" },
  { value: "CHD02", label: "缸盖M2" },
  { value: "CCK01", label: "曲轴M1" },
];
const excludedPoints = ["075","125","195","030C","048","145","065","175","178","1006","1008","1035","1040","4010","4020","1070","1075","1095","1096","1115","1126","1130","1150","1165","1195","1196","121A","121B","1235","1245","1265","1266","1290","1315","1366","1368","1405","1416","1420","1445","143B"
  ,"4050","2006","2040","2050","2055","2100","2115","2120","2135","213A","2145","2146","2150","2155","2196","2225","2236","2260","2270","2325","2355","2356","2380","2410","2420","2430","2440","2450","2476","2505","2515","6010","7010"
  ,"7020","7030","2090","303A","305B","3062","3063","3105","LG01","075_","125_","195_","LG02","003_","065_","145_","175_","178_","008_","010A","010G","015A","015B","020G","048_","150A"
]; 

watch(value3, (newValue) => {
  const selectedOption = options.find(option => option.value === newValue);
  if (selectedOption) {
    value3Label.value = selectedOption.label;
  }
});

function formatDate(d: string) {
  var date = new Date(d);
  var YY = date.getFullYear() + "-";
  var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  return YY + MM + DD;
}

var construct_url = "";
watch([value2, value3], () => {
  const start_time = formatDate(value2.value[0]);
  const end_time = formatDate(value2.value[1]);
  construct_url = "http://10.64.35.32:8000/man_ana_sql_server/get_GdHistory_data/?" + "start_time=" + start_time?.toString() + "&end_time=" + end_time?.toString() + "&sub_area=" + value3.value +"&page_size=" + 100001;
  use_show_data_in_html2();
});

const series_data3 = ref();
const series_data4 = ref();

const use_show_data_in_html2 = async () => {
  console.log(construct_url);
  const response = await axios.get(construct_url);
  const data = response.data;
  console.log(data);

  const totalProductionByEquipment = data.filter(item => !excludedPoints.includes(item.equipment_id)).reduce((acc, item) => {
    const equipmentId = item.equipment_id;
    const sum = item.sum;

    if (!acc.has(equipmentId)) {
      acc.set(equipmentId, 0);
    }

    acc.set(equipmentId, acc.get(equipmentId) + sum);

    return acc;
  }, new Map());

  series_data1.value = Array.from(totalProductionByEquipment.keys());
  series_data.value = Array.from(totalProductionByEquipment.values());

  console.log(series_data1.value);
  initChart();
};
const useShowDataInHtmlForTable = async (pointId) => {
  try {
    const start_time = formatDate(value2.value[0]);
    const end_time = formatDate(value2.value[1]);
    
    const url = `http://10.64.35.32:8000/man_ana_sql_server/get_GdHistory_data/?start_time=${start_time}&end_time=${end_time}&sub_area=${value3.value}&equipment_id=${pointId}&page_size=100001`;

    console.log(url);
    const response = await axios.get(url);
    const data = response.data.filter(item => !excludedPoints.includes(item.equipment_id));

    const processedData = data.map(item => ({
      ...item,
      equipment_id: item.equipment_id
    }));

    tableData.value = processedData;
    const hourlyProduction = new Map();
    const dailyProduction = new Map();

    data.forEach(item => {
      const productionDate = item.production_date;
      const shift = item.shift;
      const hours = Object.keys(item).filter(key => key.startsWith('hour_')).map(key => item[key]);
      const filteredHours = hours.filter(hour => hour > 0);
      filteredHours.forEach((hour, index) => {
        const hourKey = `${productionDate} 班次${shift} 小时${index + 1}`;
        hourlyProduction.set(hourKey, hour);
      });
      const dailySum = filteredHours.reduce((acc, curr) => acc + curr, 0);
      dailyProduction.set(`${productionDate} 班次${shift}`, dailySum);
    });

    if (timeView.value === 1) {
  series_data3.value = Array.from(hourlyProduction.keys());
  series_data4.value = Array.from(hourlyProduction.values());
} else {
  const dailyTotals = new Map();
  data.forEach(item => {
    const productionDate = item.production_date;
    const hours = Object.keys(item).filter(key => key.startsWith('hour_')).map(key => item[key]);
    const nonZeroHours = hours.filter(hour => hour > 0);
    const dailyTotal = nonZeroHours.reduce((acc, curr) => acc + curr, 0);
    if (dailyTotals.has(productionDate)) {
      dailyTotals.set(productionDate, dailyTotals.get(productionDate) + dailyTotal);
    } else {
      dailyTotals.set(productionDate, dailyTotal);
    }
  });
  series_data3.value = Array.from(dailyTotals.keys());
  series_data4.value = Array.from(dailyTotals.values());
};

    console.log('时间', series_data3.value);
    console.log('产量', series_data4.value);
    initChart2(pointId);
    if (processedData.length > 0) {
      lastPointId = processedData[0].equipment_id;
    }
  } catch (error) {
    console.error(error);
    ElMessage.error('加载数据失败。');
  }
};

const exportToExcel = () => {
  import('xlsx').then(XLSX => {
    const worksheet = XLSX.utils.json_to_sheet(tableData.value);
    const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const start = formatDate(value2.value[0]);
    const end = formatDate(value2.value[1]);
    const region = value3Label.value.replace(/\s/g, ''); 
    const station = lastPointId; 
    const filename = `${start}_${end}_${region}_${station}_产量情况.xlsx`;

    saveAs(new Blob([excelBuffer], { type: 'application/octet-stream' }), filename);
  });
};
</script>

<style scoped>
h3 {
  color: black;
}

.block {
  padding: 20px;
  text-align: center;
  flex: 1;
}
.block:last-child {
  border-right: none;
}
.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.el-select .el-scrollbar__wrap {
  max-height: 50px !important;
  overflow-y: auto !important;
}

/* 基本样式 */
.el-radio {
  display: flex;
  align-items: center;
}

.el-radio__inner {
  width: 20px;
  height: 20px;
  border-radius: 50%; /* 圆形 */
}

/* 选中状态 */
.el-radio__input.is-checked .el-radio__inner {
  background-color: #409EFF; /* 选中时圆点颜色 */
  border-color: #409EFF; /* 选中时边框颜色 */
}

/* 选中状态的文字颜色 */
.el-radio__label {
  color: #333;
}

.el-radio__input.is-checked + .el-radio__label {
  color: #409EFF; /* 选中时文字颜色 */
}
</style>
